<?php

/**
 * Description of Reportes
 *
 * @author JeyDotC
 * 
 * @export Modules
 * @export-metadata RequiredRoles:Agencia
 */
class Reportes extends Module {

    public function index() {
        $this->display("index");
    }

    public function recaladas() {
        $this->assign("action", $this->route->action("reporteRecalada"));

        $this->display("recaladas");
    }

    public function reporteRecalada() {
        Loader::using("ext::libs::dompdf::dompdf_config.inc");

        $format = "d-m-Y H:i";
        $inicio = $this->request->post("fechaInicio");
        $fin = $this->request->post("fechaFin");

        $formatter = new MicrosoftDateFormatter();
        $fechaInicio = MicrosoftDateFormatter::toJSON($inicio, $format);
        $fechaFin = MicrosoftDateFormatter::toJSON($fin, $format);

        $recaladas = $this->components->Recaladas->listarPorEta($fechaInicio, $fechaFin, 1);

        if ($recaladas != null) {
            foreach ($recaladas as /* @var $recalada Recaladas */$recalada) {
                $tipoRecalada = TiposRecaladas::valueToString($recalada->getTipoRecalada());
                $recalada->setTipoRecalada($tipoRecalada);
                
                $recalada->setEtd($formatter->fromJSON($recalada->getEtd(), $format));
                $recalada->setEta($formatter->fromJSON($recalada->getEta(), $format));

                if ($recalada->getViajes()) {
                    $id = $recalada->getViajes()->getIdTerminal();
                    $terminal = $this->components->Terminales->getById($id);
                    $recalada->getViajes()->setTerminales($terminal);
                }

                if ($recalada->getViajes1()) {
                    $id = $recalada->getViajes1()->getIdTerminal();
                    $terminal = $this->components->Terminales->getById($id);
                    $recalada->getViajes1()->setTerminales($terminal);
                }

                $recalada->setCutoffDocumental($formatter->fromJSON($recalada->getCutoffDocumental(), $format));
                $recalada->setCutoffFisico($formatter->fromJSON($recalada->getCutoffFisico(), $format));
                $recaladaPuerto = $this->components->Recaladas->getRecaladaPuerto($recalada->getIdRecalada());

                if ($recaladaPuerto) {
                    $recalada->setRecaladasPuertos($recaladaPuerto);
                }
            }
        }else{
            $recaladas = array();
        }

        $this->assign("recaladas", $recaladas);

        $html = $this->renderGet("recaladas.pdf");

        $dompdf = new DOMPDF();
        $dompdf->load_html($html);
        $dompdf->render();
        $filename = "Reporte recaladas $inicio-$fin.pdf";
        $dompdf->stream(str_replace(":", "_", $filename));
    }

}

?>
